package com.nova.bluetooth.ui.ai.translate;


import static com.nova.bluetooth.base.CommonMessageWrap.ACTION_AIUI_TTS_RESULT;
import static com.nova.bluetooth.xunFeiSDK.engine.EngineConstants.RECORDER_DATA;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.nova.bluetooth.MyApp;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.CommonMessageWrap;
import com.nova.bluetooth.databinding.ActivityAudioTranslatingBinding;
import com.nova.bluetooth.helpUtils.AppUtil;
import com.nova.bluetooth.helpUtils.DateUtil;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.NetworkUtil;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.StorageUtil;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;
import com.nova.bluetooth.ui.ai.MyAiUiViewModel;
import com.nova.bluetooth.webIat.WebXunFeiTWS;
import com.nova.bluetooth.widget.AutoScrollTextView;
import com.nova.bluetooth.xunFeiSDK.engine.AiuiEngine;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.recorder.SystemRecorder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 同声听译新功能（音频==》语音识别===》文字翻译 || 边识别语音边翻译 功能）
 */
@SuppressLint("MissingPermission")
public class AudioTranslatingActivity extends PermissionManageActivity implements
        MyAiUiViewModel.OnAiUiRecognizeListener, WebXunFeiTWS.OnIATWSRecognizeListener {
    private ActivityAudioTranslatingBinding binding;
    private MyTranslateViewModel viewModel;

    /***************************SCO连接 start****************************/
    private void setupBluetooth() {
        // 开启蓝牙采集音频
//        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        manager.setBluetoothScoOn(true);
//        manager.startBluetoothSco();
    }

    private void stopBluetoothSco() {
        // 停止蓝牙音频采集并注销广播接收器
//        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        manager.setBluetoothScoOn(false);
//        manager.stopBluetoothSco();
    }

    private void registerSCOReceiver() {
        // 注册蓝牙状态广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(bluetoothStateReceiver, filter);
    }

    private void unregisterSCOReceiver() {
        unregisterReceiver(bluetoothStateReceiver);
    }

    private final BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED.equals(intent.getAction())) {
                int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);

                if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
                    // 蓝牙耳机已连接，可以进行音频采集了
                } else if (state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
                    // 蓝牙耳机断开连接，需要处理相应逻辑
                }
            }
        }
    };
    /***************************end****************************/


    /*******************************语言选择弹窗*********************************/
    private String mLeftLanguageName = "普通话";
    private String mRightLanguageName = "英语";
    private String asrLanguageCode = "zh_cn";
    private String translateLanguageCode = "en";

    private String asrLanguageAccentCode = "mandarin";
    private int asrLanguageAccentType = 1; //1语言 2方言
    public static final int SHOW_ASR_LANGUAGE_DIALOG = 0x01;
    public static final int SHOW_TRANSLATE_LANGUAGE_DIALOG = 0x02;
    private boolean isShowLanguageDialogLeft = true;

    /**
     * 切换识别语言和翻译语言（两者互换）
     */
    private void switchLanguageType() {
        //切换语言
        String switchLanguageName = mRightLanguageName;
        mRightLanguageName = mLeftLanguageName;
        mLeftLanguageName = switchLanguageName;

        translateLanguageCode = NovaTransformLanguageCodeUtil.
                getTranslateBeanByAsrLanguageName(mRightLanguageName).getLanguageCode();

        LanguageSelectBean asrLanguageSelectBean = NovaTransformLanguageCodeUtil.getAsrLanguageBeanByTranslateName(mLeftLanguageName);
        asrLanguageCode = asrLanguageSelectBean.getLanguageCode();
        asrLanguageAccentType = asrLanguageSelectBean.getType();
        asrLanguageAccentCode = asrLanguageSelectBean.getLanguageCode();
    }

    private void updateSwitchLanguageUI() {
        binding.tvRightLanguage.setText(mRightLanguageName);
        binding.tvLeftLanguage.setText(mLeftLanguageName);

        resetSpeakingScene();
    }

    /**
     * 设置语音识别语言
     */
    private void resetSpeakingScene() {
//        if (asrLanguageCode.contains("cn")) {
//            aiUiViewModel.setScene(true);
//        } else if (asrLanguageCode.contains("en")) {
//            aiUiViewModel.setScene(false);
//        }
        setAsrAndTranslateLanguageCode();

        LogUtil.d("test==>设置识别语言：" + " asrLanguageCode " + asrLanguageCode +
                " asrLanguageAccentCode " + asrLanguageAccentCode +
                " asrLanguageAccentType " + asrLanguageAccentType);
        webIATWSManage.setScene(asrLanguageCode, asrLanguageAccentCode, asrLanguageAccentType);
    }

    private void setAsrAndTranslateLanguageCode() {
        LanguageSelectBean mAsrLanguageBean = NovaTransformLanguageCodeUtil.getAsrLanguageBeanByTranslateName(mLeftLanguageName);
        asrLanguageCode = mAsrLanguageBean.getLanguageCode();
        translateLanguageCode = NovaTransformLanguageCodeUtil.getTranslateBeanByAsrLanguageName(mRightLanguageName).getLanguageCode();

        asrLanguageAccentType = mAsrLanguageBean.getType();
        if (asrLanguageAccentType == 2) {
            asrLanguageAccentCode = mAsrLanguageBean.getLanguageCode();
        } else {
            asrLanguageAccentCode = "mandarin";
        }

        viewModel.asrTargetLanguage.setValue(asrLanguageCode);
        viewModel.translationTargetLanguage.setValue(translateLanguageCode);
        LogUtil.d("test==>设置识别语言：" + " translateLanguageCode " + translateLanguageCode);

    }


    private StringBuffer translateStringBuffer = new StringBuffer();
    private StringBuffer originalStringBuffer = new StringBuffer();

    public void clearTranslateString() {
        if (translateStringBuffer.length() > 0) {
            translateStringBuffer.delete(0, translateStringBuffer.length());
        }
    }

    public void clearOriginalString() {
        if (originalStringBuffer.length() > 0) {
            originalStringBuffer.delete(0, originalStringBuffer.length());
        }

    }

    private MyAiUiViewModel aiUiViewModel;
    private WebXunFeiTWS webIATWSManage;
    //    private AiTranslateAudioViewModel mAiTranslateViewModel;
    private MyHandler myHandler;
//    private CommonViewModel commonViewModel;


    private static class MyHandler extends Handler {
        public static final int WAVE_AMPLITUDE_TAG = 0x01;
        public static final int TRANSLATE_BAIDU_TAG = 0x02;
        public static final int SEND_END_DATA_TAG = 0x04;
        public static final int TIMEOUT_TRANSLATE_BAIDU_TAG = 0x05;
        public static final int TIMER_TAG = 0x03;
        AudioTranslatingActivity activity;

        public MyHandler(WeakReference<AudioTranslatingActivity> weakReference) {
            activity = weakReference.get();
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WAVE_AMPLITUDE_TAG:
                    break;
                case TIMEOUT_TRANSLATE_BAIDU_TAG:
                    activity.setResultToUI(activity.asrNoSplicingResult, 2, activity.binding.etContent);
//                    activity.originalStringBuffer.append(activity.asrNoSplicingResult);
                    activity.viewModel.baiduTranslation(
                            activity.asrNoSplicingResult,
                            Objects.requireNonNull(activity.translateLanguageCode));
                    break;
                case TRANSLATE_BAIDU_TAG:
                    activity.viewModel.baiduTranslation(
                            activity.asrNoSplicingResult,
                            Objects.requireNonNull(activity.translateLanguageCode));
                    break;
                case TIMER_TAG:
                    activity.updateTimer();
                    break;
                case SEND_END_DATA_TAG:
                    activity.webIATWSManage.sendEndData();
                    break;
            }
        }
    }


    private long lastAudioData = 0;  //记录上一次收到声音推流的时间

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommonMessageWrap message) {
        switch (message.getEventCode()) {
            case ACTION_AIUI_TTS_RESULT:
                AIUIEvent aiuiEvent = (AIUIEvent) message.getObject();
                if (aiuiEvent.eventType == AIUIConstant.CMD_STOP_SAVE) {
                    if (aiuiEvent.arg1 == 5) { //语音合成完毕
                        MyAiUiViewModel.TTSIsStart = false;
                        LogUtil.d("TTS 播放完毕");

                        if (!AppUtil.isForeground(AudioTranslatingActivity.this)) {
                            return;
                        }

                        if (ttsQueue.size() > 0 && Boolean.TRUE.equals(viewModel.ttsIsOpen.getValue())) {
                            binding.getRoot().postDelayed(() -> startTTSByQueue(), 500);
                        } else {
                            boolean isSelected = binding.includeBottom.ivAudioPlay.isSelected();
                            if (!isSelected) {
                                //重新打开录音
                                ttsQueue.clear();
                                showPermissionRequiresDialog();
                            }
                        }

                    }
                }
                break;

            case RECORDER_DATA:
                lastAudioData = System.currentTimeMillis();
//                byte[] audioData = (byte[]) message.getObject();
//                double db = AudioUtil.calculateDecibel(audioData);
//                double amplitude = AudioUtil.calculateAmplitude(audioData);
//                LogUtil.i("test====说话声音振幅 amplitude： " + amplitude + " Decibel:" + db);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        EventBusUtil.register(this);
        initBinding();
        setContentView(binding.getRoot());
//        initImmersionBar(Color.TRANSPARENT, Color.TRANSPARENT, true);
        initView();
        initData();
        observe();
        myHandler = new MyHandler(new WeakReference<>(AudioTranslatingActivity.this));
        getOnBackPressedDispatcher().addCallback(this, callback);
        initRecordPath();

        registerSCOReceiver();

        AiuiEngine.setAiuiEngineOpen = false;


        // 开启屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setPaddingBottom(this,binding.getRoot());
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtil.unRegister(this);
        aiUiViewModel.setOnAiUiRecognizeListenerAndClear(null);
        aiUiViewModel.destroyAiUiAllEngine();
        webIATWSManage.sendEndData();
        webIATWSManage.onDestroy();

        myHandler.removeCallbacksAndMessages(null);

        //如果正在TTS中，停止他
        stopTTS();
        deleteUnUserAudioFile();

        seconds = 0;
        clearTranslateString();
        clearOriginalString();

        stopBluetoothSco();
        unregisterSCOReceiver();

        AiuiEngine.setAiuiEngineOpen = true;  //恢复默认设置

        // 关闭屏幕常亮
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // 在这里处理返回键按下的逻辑
            // 如果要拦截返回键，可以在这里添加你的逻辑，否则调用 isEnabled() 方法检查是否应该交给默认行为
            goOut();
//            if (!showUserBackTipsDialog(false)) {
//                // 处理返回键按下的逻辑
//                // 例如，你可以在这里执行一些操作，然后调用 finish() 关闭 Activity
//                goOut();
//            }
        }
    };

    private void deleteUnUserAudioFile() {
        File unUserFile = new File(SystemRecorder.saveRecordPath);
        if (unUserFile.exists()) {
            unUserFile.delete();
            SystemRecorder.saveRecordAudioTimeSnippet = 0;
        }
    }

    /**
     * 退出保存
     */
    private void goOutSaveData() {
//        if (viewModel.translatingBeanList.getValue().size() > 0) {
//            try {
//                String originalPath = SystemRecorder.saveRecordPath;
//                // 将 ".pcm" 替换为 ".wav"
//                String newPath = originalPath.replace(".pcm", "");
//                ConvertUtils.convertPcm2Wav(SystemRecorder.saveRecordPath, newPath);
//                String uploadUrl = newPath + ".wav";
//                mAiTranslateViewModel.getCredential(uploadUrl);
//                LogUtil.d("将上传的音频路径：" + uploadUrl);
//                showLoadingDialog();
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
    }

    private void initBinding() {
        binding = ActivityAudioTranslatingBinding.inflate(getLayoutInflater());
        viewModel = new ViewModelProvider(this).get(MyTranslateViewModel.class);

        aiUiViewModel = new ViewModelProvider(MyApp.getInstance()).get(MyAiUiViewModel.class);
        viewModel.enableRefresh.set(false);
        binding.setVm(viewModel);
        binding.setLifecycleOwner(this);
        MyOnClickEvent myOnClickEvent = new MyOnClickEvent();
        binding.setOnClick(myOnClickEvent);
        binding.includeBottom.setOnClick(myOnClickEvent);
        binding.includeBottom.setVm(viewModel);
//        mBinding = binding;
    }

    private void initView() {
        aiUiViewModel.initSDK(this);
        aiUiViewModel.setOnAiUiRecognizeListenerAndClear(this);
        webIATWSManage = WebXunFeiTWS.getInstance();
        webIATWSManage.clearDiscard();
        webIATWSManage.setOnIATWSRecognizeListener(this);

        //给默认值
        viewModel.asrTargetLanguage.setValue(asrLanguageCode);
        viewModel.translationTargetLanguage.setValue(translateLanguageCode);
        updateSwitchLanguageUI();
        binding.tvEmpty.setVisibility(View.VISIBLE);
        binding.turnResultScroller.setVisibility(View.GONE);
    }

    private void initData() {
        //获取服务端听写识别
//        commonViewModel.getIatLanguageList();

        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
    }

    private void observe() {
        viewModel.baiduTranslationResult.observe(this, textTranslateResult -> {
            if (Objects.equals(textTranslateResult.getCode(), 200)) {
                String translateString = textTranslateResult.getData();
                binding.etContentTranslate.appendText(translateString);
                binding.etContentTranslate.scrollToBottom();
                translateContextTTS(textTranslateResult.getData());
            }
        });

        viewModel.insertSuccess.observe(this, result -> {
            if (result) {
                goOut();
            }
        });
    }

    private void updateSelectedLangUI(List<LanguageSelectBean> dataList) {
        mLeftLanguageName = dataList.get(0).getLanguageName();
        mRightLanguageName = dataList.get(1).getLanguageName();
        binding.tvRightLanguage.setText(mRightLanguageName);
        binding.tvLeftLanguage.setText(mLeftLanguageName);
    }


    private boolean isAiTranscriptionMode() {
        return false;
    }

    public class MyOnClickEvent extends OnClickEvent {
        @Override
        public void singleClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_switch) {
                boolean isTranslating = Boolean.TRUE.equals(viewModel.isTranslating.getValue());
                if (isTranslating) {
                    ToastUtils.show("翻译中");
                } else {
                    switchLanguageType();
                    updateSwitchLanguageUI();
                }
            } else if (id == R.id.iv_back) {
                onBackPressed();
            } else if (id == R.id.iv_audio_play) {
                boolean isSelected = binding.includeBottom.ivAudioPlay.isSelected();
                if (isSelected) {
                    stopRecord();
                } else {
                    showPermissionRequiresDialog();
                }
            } else if (id == R.id.shadow_switch_voice) {
                boolean isOpen = viewModel.ttsIsOpen.getValue();
//                    ToastUtils.show(isOpen ? "语音合成已关闭" : "语音合成已打开");
                viewModel.ttsIsOpen.setValue(!isOpen);
            }
        }
    }

    private void goOut() {
        if (isRecording) {
            stopRecord();
        }
        stopTTS();
        aiUiViewModel.clearRecognitionText();
        finish();
    }


    Queue<String> ttsQueue = new LinkedBlockingQueue<>();

    private void translateContextTTS(String str) {
        if (Boolean.TRUE.equals(viewModel.ttsIsOpen.getValue())) {
            // 耳机在推送中时，播放的TTS听不到，所以  stopRecord() ，让推送数据停止
            if (!isAiTranscriptionMode()) {
                stopRecord(); //先停止录音，避免把TTS合成的声音也录进去 (手机模式才回有此问题)
            }
            ttsQueue.offer(str);  //添加播放数据到列队
            if (ttsQueue.size() == 1) startTTSByQueue();
        }
    }

    private void startTTSByQueue() {
        if (ttsQueue.size() > 0 && !MyAiUiViewModel.TTSIsStart) {  //有东西要播且TTS空闲就开始播放,正在播就会等播完了再调这个方法
            String ttsRobot = NovaTransformLanguageCodeUtil.getTranslateBeanByTranslateLanguageName(mRightLanguageName).getSpeakerCode();
            MyAiUiViewModel.TTS_ROBOT = ttsRobot;
            aiUiViewModel.startTTSBySdk(ttsQueue.poll());
        }
    }

    private void stopTTS() {
        if (Boolean.TRUE.equals(viewModel.ttsIsOpen.getValue())) {
            aiUiViewModel.stopTTS();
        }
    }

    /******************************权限管理******************************/
    private void showPermissionRequiresDialog() {
        getRecordAudioPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                initAiUiRecord();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取录音权限用于录音翻译");
    }


    /**********************************录音计时**************************************/
    private boolean isTimerRunning = false;
    private int seconds = 0;

    private void startTimer() {
        if (!isTimerRunning) {
            isTimerRunning = true;
            myHandler.postDelayed(timerRunnable, 1000);
        }
    }

    private void pauseTimer() {
        if (isTimerRunning) {
            isTimerRunning = false;
            myHandler.removeCallbacks(timerRunnable);
        }
    }

    private void updateTimer() {
        seconds++;
        String currentProgress = DateUtil.getDateToString(seconds * 1000, DateUtil.H_M_S, "UTC");
        binding.includeBottom.tvTimer.setText(String.valueOf(currentProgress));
        myHandler.postDelayed(timerRunnable, 1000);
    }

    private final Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            myHandler.sendEmptyMessage(MyHandler.TIMER_TAG);

            checkNet();
            checkRecorderIsRunning();
        }
    };

    private int times_tag = 0;

    private void checkNet() {
        new Thread(() -> {
            String hostUrl_def = "iat-api.xfyun.cn";
            long error_time = NetworkUtil.getPingTime(hostUrl_def);
            LogUtil.i("test===>网络延时检测：" + error_time);
            if (error_time > 150) {
                times_tag++;
            }

            if (times_tag > 5) {
                binding.getRoot().post(() -> ToastUtils.show("网络异常"));
                times_tag = 0;
            }
        }).start();
    }

    private boolean setRecordIsStop = false;

    private void checkRecorderIsRunning() {
        boolean isSelected = binding.includeBottom.ivAudioPlay.isSelected(); //正在录音为 true
        boolean audioIsRunning = System.currentTimeMillis() - lastAudioData < 2000;
        if (isSelected && !audioIsRunning) {
            if (setRecordIsStop) {
                LogUtil.e("test===>开启录音但检测到未推流，重新开启录音initAiUiRecord");
                initAiUiRecord();
                setRecordIsStop = false;
            } else {
                aiUiViewModel.stopRecord();
                setRecordIsStop = true;
                LogUtil.e("test===>开启录音但检测到未推流，关闭录音stopRecord");
            }

        }

    }

    /****************************************WebAI语音听写识别*****************************************/

    @Override
    public void onWebAsrResult(String result, int status) {
        if (result.isEmpty()) return;

        LogUtil.i(TAG + "识别结果展示 onAsrResult：" + result);
        asrNoSplicingResult = result;

        binding.getRoot().post(() -> {
            if (binding.tvEmpty.getVisibility() == View.VISIBLE) {
                binding.tvEmpty.setVisibility(View.GONE);
                binding.turnResultScroller.setVisibility(View.VISIBLE);
            }

            myHandler.removeMessages(MyHandler.SEND_END_DATA_TAG);
            myHandler.removeMessages(MyHandler.TIMEOUT_TRANSLATE_BAIDU_TAG);
            if (status == 2) {
                setResultToUI(result, 2, binding.etContent);
//                originalStringBuffer.append(result);
                myHandler.sendEmptyMessage(MyHandler.TRANSLATE_BAIDU_TAG);
            } else {
                setResultToUI(result, 0, binding.etContent);
//                binding.etContent.setText(originalStringBuffer.toString() + result);
                myHandler.sendEmptyMessageDelayed(MyHandler.SEND_END_DATA_TAG, 5000);//用于触发vad结束符合
                myHandler.sendEmptyMessageDelayed(MyHandler.TIMEOUT_TRANSLATE_BAIDU_TAG, 6000);
            }
        });
    }

    private void setResultToUI(String data, int type, AutoScrollTextView textView) {
        LogUtil.d("test======>type:" + type + " result:" + data);
        boolean isTypeZero = (type == 0);
        boolean isTypeTwo = (type == 2);

        if (isTypeZero && textView.lastStartIndex == -1) {
            textView.appendText(data);
        } else {
            textView.replaceLastModification(data);
            if (isTypeTwo) {
                textView.resetIndex();
            }
        }

        textView.scrollToBottom();
    }

    @Override
    public void onWebRecordStatus(boolean recording) {
        isRecording = recording;
    }

    @Override
    public void onWebStartSpeaking() {
        viewModel.isTranslating.postValue(true);  //有识别结果，令APP进入翻译中状态
    }

    /******************************* AIUI 语音助手结果监听******************************/

    private boolean isRecording = false;

    private void initAiUiRecord() {
        //同声听译功能不保存音频数据
        EngineConstants.saveAudio = false;
        //启动语音听写接口识别
        webIATWSManage.runWebIATWSWebSocket();

        //初始化录音(唤醒直接识别)
        aiUiViewModel.initRecorder();

        binding.includeBottom.ivAudioPlay.setSelected(true);
        startTimer();
    }

    private void initRecordPath() {
        String suffix = "pcm";
        String fileName = "Ai_Translate_Recorder" + "." + suffix;

        String audioDir = StorageUtil.getAudioDir();
        File musicDir = new File(audioDir);
        File file = new File(musicDir, "/" + fileName); //文件夹路径 + 文件名
        SystemRecorder.saveRecordPath = file.getAbsolutePath(); //设置录音文件路径存放录音
        LogUtil.d("录音路径 saveRecordPath = " + SystemRecorder.saveRecordPath);
        SystemRecorder.saveRecordAudioTimeSnippet = 0; //初始化，时间记录TAG为0
        SystemRecorder.mMultiple = SystemRecorder.IAT_MULTIPLE;
    }

    private void stopRecordAndRecognize() {
        aiUiViewModel.clearRecognitionText();
        aiUiViewModel.stopRecord();

        webIATWSManage.stopWebSocketThread();
    }

    private void stopRecord() {
        aiUiViewModel.stopRecord();
        webIATWSManage.stopWebSocketThread();
        binding.includeBottom.ivAudioPlay.setSelected(false);
        pauseTimer();
    }

    @Override
    public void onStartSpeaking() {
        viewModel.isTranslating.setValue(true);  //有识别结果，令APP进入翻译中状态

        if (isAiTranscriptionMode()) {
            //优先录音识别，如果有在tts 就停了他
//            stopTTS();
        }
    }

    private String asrNoSplicingResult = "";

    @Override
    public void onAsrResult(String result) {
        LogUtil.i(TAG + "识别结果展示 onAsrResult：" + result);

        if (binding.tvEmpty.getVisibility() == View.VISIBLE) {
            binding.tvEmpty.setVisibility(View.GONE);
            binding.turnResultScroller.setVisibility(View.VISIBLE);
        }
        binding.etContent.setText(result);

        //超过n秒没新内容就去翻译
        myHandler.removeMessages(MyHandler.TRANSLATE_BAIDU_TAG);
        myHandler.sendEmptyMessageDelayed(MyHandler.TRANSLATE_BAIDU_TAG, 1000);
    }

    @Override
    public void onAsrNoSplicingResult(String result) {
        LogUtil.i(TAG + "识别结果展示：" + result);
        asrNoSplicingResult = result;
    }

    @Override
    public void onAsrNoSplicingResultEnd(boolean isResultEnd) {
        if (isResultEnd) {
            LogUtil.i(TAG + "onAsrNoSplicingResultEnd：" + isResultEnd);
        }
    }

    @Override
    public void onRecordStatus(boolean recording) {
        isRecording = recording;
    }
}